﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace SCCL2010
{
    public static class Libraries
    {

        private static void EnsureLibrary(SPWeb oWeb, string cDisplayName, string cInternalName)
        {
            if (!Lists.HasList(oWeb, cDisplayName))
            {
                CreateLibrary(oWeb, cInternalName, cInternalName);
            }
        }



        /// <summary>
        /// Creates the Library based on the supplied Library Name.
        /// </summary>
        /// <param name="oWeb"></param>
        /// <param name="cLibInternalName"></param>
        /// <param name="cLibName"></param>
        public static void CreateLibrary(SPWeb oWeb, String cLibInternalName, String cLibName)
        {
            try
            {
                CreateLibrary(oWeb, cLibInternalName);
                if (Lists.HasList(oWeb, cLibInternalName))
                {
                    SPDocumentLibrary oDocs = (SPDocumentLibrary)oWeb.Lists[cLibInternalName];
                    if (cLibInternalName != cLibName)
                    {
                        oDocs.Title = cLibName;
                    }
                    oDocs.Hidden = false;
                    oDocs.Update();
                }
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleError(oWeb, "Libraries.CreateLibrary", ex);
            }
        }



        /// <summary>
        /// Creates a SharePoint Document Library
        /// </summary>
        /// <param name="oWeb"></param>
        /// <param name="cLibName"></param>
        public static void CreateLibrary(SPWeb oWeb, String cLibName)
        {
            try
            {
                oWeb.Lists.Add(cLibName, "", SPListTemplateType.DocumentLibrary);
                SPList oList = oWeb.Lists[cLibName];
                oList.Hidden = false;
                oList.Update();
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleError(oWeb, "Libraries.CreateLibrary", ex);
            }
        }

        /// <summary>
        /// Checks if the file exists.
        /// </summary>
        /// <param name="oFolder"></param>
        /// <param name="cFileName"></param>
        /// <returns>returns a boolean value if the file exists based on the FileName.</returns>
        public static bool HasFile(SPFolder oFolder, String cFileName)
        {
            try
            {
                foreach (SPFile file in oFolder.Files)
                {
                    if (file.Name == cFileName) return true;
                }
            }
            catch (Exception ex)
            {
                ErrorHandling.HandleError(oFolder.ParentWeb, "Libraries.HasFile", ex);
                return true;
            }
            return false;
        }

    }
}
